<template>
  <Header title="退款退货" :hasRight="true" @save="saveReturn" />

  <div class="refund">
    <div class="orderBox">
      <div
        class="orderItemBox"
        v-for="(orderItem, orderItemIndex) in orderData.orderItemsForFront"
        :key="orderItemIndex"
      >
        <nut-checkbox
          v-model="orderItem.selected"
          @change="calcuteRefundAmount"
        ></nut-checkbox>
        <OrderItem :orderItem="orderItem" />
      </div>
    </div>
    <div class="form">
      <nut-form :model-value="formData" :rules="formRules" ref="ruleForm">
        <nut-form-item label="支付金额" body-align="right">
          <nut-price :price="orderData.payAmount" size="normal" symbol="¥" />
        </nut-form-item>
        <nut-form-item label="退款金额" body-align="right">
          <nut-price :price="formData.refundAmount" size="normal" symbol="¥" />
        </nut-form-item>
        <nut-cell
          title="退款类型"
          :desc="refundType.text"
          @click="visibleStatus.refundType = true"
        ></nut-cell>
        <nut-popup position="bottom" v-model:visible="visibleStatus.refundType">
          <nut-picker
            v-model="refundType.value"
            :columns="refundTypeList"
            @cancel="visibleStatus.refundType = false"
            @confirm="selectRefundType"
          >
          </nut-picker>
        </nut-popup>
        <nut-form-item label="退款原因" prop="reason">
          <nut-textarea
            placeholder=" "
            v-model="formData.reason"
            :rows="5"
            limit-show
            max-length="100"
          />
        </nut-form-item>
      </nut-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 显示状态控制
const visibleStatus = reactive({
  refundType: false,
});

// 路由参数
const routeParams = reactive({
  orderId: route.query.orderId,
  orderItemId: route.query.orderItemId,
});

// 退款类型
const refundType = reactive({
  value: ["0"],
  text: "仅退款",
});
const refundTypeList = reactive([
  { text: "仅退款", value: "0" },
  { text: "退款退货", value: "1" },
  { text: "换货", value: "2" },
]);
const selectRefundType = ({ selectedValue, selectedOptions }) => {
  refundType.value = [selectedOptions[0].value];
  refundType.text = selectedOptions[0].text;
  visibleStatus.refundType = false;
};

// 表单数据
const ruleForm = ref(null);
const formData = reactive({
  reason: "",
  refundAmount: 0,
});
const formRules = reactive({
  reason: [{ required: true, message: "请填写退款原因" }],
});

// 订单数据
const orderData = reactive({
  orderItems: [],
});

// 重复提交token
const repeatSubmitToken = ref(null);
const getRepeatSubmitToken = () => {
  proxy.$thirdApi.common
    .repeatSubmitToken()
    .then((res) => {
      repeatSubmitToken.value = res.data;
    })
    .catch((error) => {});
};

// 计算订单退款金额
const calcuteRefundAmount = () => {
  var refundAmount = 0;
  orderData.orderItemsForFront.forEach((orderItem) => {
    refundAmount += orderItem.selected ? parseFloat(orderItem.totalAmount) : 0;
  });
  formData.refundAmount = refundAmount;
};

// 申请退款
const saveReturn = () => {
  ruleForm.value.validate().then(({ valid, errors }) => {
    if (valid) {
      var orderItemIds = [];
      orderData.orderItemsForFront.forEach((orderItem) => {
        if (orderItem.selected) {
          orderItemIds.push(orderItem.id);
        }
      });
      if (orderItemIds.length <= 0) {
        proxy.$showToast.fail("请选择要退款的商品");
        return;
      }
      proxy.$orderApi.refund
        .applyReturn({
          repeatSubmitToken: repeatSubmitToken.value,
          orderId: routeParams.orderId,
          refundType: refundType.value[0],
          orderItemIds: orderItemIds,
          reason: formData.reason,
        })
        .then((res) => {
          router.back();
        });
    }
  });
};

// 设置选中状态
const setSelectedStatus = (orderItem) => {
  var orderItemId = routeParams.orderItemId;
  if (null == orderItemId) {
    orderItem.selected = true;
  } else if (orderItem.id == orderItemId) {
    orderItem.selected = true;
  } else {
    orderItem.selected = false;
  }
};

// 过滤掉已售后的子项
const filterRefundedOrderItem = (data) => {
  var orderItems = [];
  data.orderItemsForFront.forEach((orderItem) => {
    if (orderItem.showApplyReturnBtn) {
      setSelectedStatus(orderItem);
      orderItems.push(orderItem);
    }
  });
  data.orderItemsForFront = orderItems;
  return data;
};

// 页面加载完成
onMounted(() => {
  getRepeatSubmitToken();
  proxy.$orderApi.order
    .info(routeParams.orderId)
    .then((res) => {
      Object.assign(orderData, filterRefundedOrderItem(res.data));
      calcuteRefundAmount();
    })
    .catch((error) => {});
});
</script>

<style lang="less" scoped>
.refund {
  margin: 5px;
  .orderBox {
    padding: 10px;
    background: #fff;
    border-radius: 5px;
    .orderItemBox {
      display: flex;
      margin-bottom: 10px;
      .nut-checkbox {
        margin-right: 0px;
      }
    }
    .orderItemBox:last-child {
      margin-bottom: 0px;
    }
  }
}
</style>